#include "triangle.hpp"
#include "line.hpp"
#include <algorithm>
#include <iostream>

using namespace std;
using namespace sf;

std::vector<sf::Vector2f> createTriangle(sf::Vector2f p0, sf::Vector2f p1, sf::Vector2f p2)
{
    std::vector<sf::Vector2f> points;
    if (p1.y < p0.y) {
        swap(p0, p1);
    }
    if (p2.y < p0.y) {
        swap(p0, p2);
    }
    if (p2.y < p1.y) {
        swap(p1, p2);
    }
    auto line01 = createLine(p0, p1);
    auto line12 = createLine(p1, p2);
    auto line02 = createLine(p0, p2);

    line01.insert(line01.end(), line12.begin(), line12.end());
    line01.insert(line01.end(), line02.begin(), line02.end());

    return line01;
}

std::vector<sf::Vector2f> createFilledTriangle(sf::Vector2f p0, sf::Vector2f p1, sf::Vector2f p2)
{
    std::vector<sf::Vector2f> points;
    if (p1.y < p0.y) {
        swap(p0, p1);
    }
    if (p2.y < p0.y) {
        swap(p0, p2);
    }
    if (p2.y < p1.y) {
        swap(p1, p2);
    }
    auto x01 = interpolate(p0.y, p1.y, p0.x, p1.x);
    x01.pop_back();
    auto x12 = interpolate(p1.y, p2.y, p1.x, p2.x);
    x01.insert(x01.end(), x12.begin(), x12.end());

    // 判断线在左边还是在右边
    auto& x012 = x01;
    auto x02 = interpolate(p0.y, p2.y, p0.x, p2.x);
    // 随便取一条线
    decltype(x01) xLeft = std::move(x012), xRight = std::move(x02);
    auto mid = xLeft.size() / 2;
    if (xRight[mid] < xLeft[mid]) {
        swap(xLeft, xRight);
    }
    // 绘制水平线
    for (int y = p0.y; y <= p2.y; y++) {
        for (float x = xLeft[y - p0.y]; x <= xRight[y - p0.y]; x += 1.0f) {
            points.push_back({x, y * 1.0f});
        }
    }
    return points;
}